import { defineStore } from 'pinia'
import { getAccessToken, getRole, isAuth, getUser } from '@/utils/userUtil'
import { type Course, type GPA, type Score } from '@/models/course'
import { GetCourseSchedule, GetScore } from '@/controllers/courseController'
import { GetEstimation } from '@/controllers/userController'
//用户
export const useUserStore = defineStore('user', {
  state: () => ({
    accessToken: getAccessToken(),
    isLogin: isAuth(),
    role: getRole(),
    account: getUser().account,
    name: getUser().name,
    profile: getUser().profile,
    userId: getUser().userId
  }),
  actions: {
    login() {
      this.accessToken = getAccessToken()
      this.isLogin = true
      this.role = getRole()
      this.account = getUser().account
      this.name = getUser().name
      this.profile = getUser().profile
      this.userId = getUser().userId
    },
    logout() {
      this.accessToken = ''
      this.isLogin = false
      this.role = ''
      this.account = ''
      this.profile = ''
      this.name = ''
      this.userId = 0
      useNaviStore().clear()
      useCourseStore().clear()
      useScoreStore().clear()
      useEstimationStore().clear()
    },
    refreshState() {
      this.accessToken = getAccessToken()
      this.isLogin = isAuth()
      this.role = getRole()
      this.account = getUser().account
      this.profile = getUser().profile
      this.name = getUser().name
      this.userId = getUser().userId
      useNaviStore().clear()
      useCourseStore().clear()
      useScoreStore().clear()
      useEstimationStore().clear()
    }
  }
})
//导航栏组件
export const useNaviStore = defineStore('navi', {
  state: () => ({
    chipGroup: [
      {
        index: 0,
        name: '首页',
        route1: 'home',
        route2: '',
        route3: ''
      }
    ],
    selectedChip: 0
  }),

  actions: {
    addChip(name: string, route1: string, route2: string, route3: string) {
      const exists = this.chipGroup.some((val) => {
        if (val.name === name) {
          this.selectedChip = val.index
          return true // 表示找到匹配项，停止遍历
        }
        return false // 没有找到匹配项
      })

      if (!exists) {
        if (this.chipGroup.length === 12) {
          this.chipGroup.pop()
        }
        this.chipGroup.push({
          index: this.chipGroup.length,
          name: name,
          route1: route1,
          route2: route2,
          route3: route3
        })
        this.selectedChip = this.chipGroup.length - 1
      }
    },
    deleteChip(index: number) {
      if (index == this.selectedChip) {
        this.selectedChip = 0
      }
      this.chipGroup.splice(index, 1)
      this.chipGroup.forEach((val, index) => {
        if (val.index != index) {
          val.index = index
        }
      })
      if (index < this.selectedChip) this.selectedChip--
    },
    clear() {
      this.chipGroup = [
        {
          index: 0,
          name: '首页',
          route1: 'home',
          route2: '',
          route3: ''
        }
      ]
      this.selectedChip = 0
    }
  }
})

//课程
export const useCourseStore = defineStore('course', {
  state: () => ({
    courses: [] as Course[],
    initialized: false
  }),
  actions: {
    async init() {
      if (!this.initialized) {
        try {
          this.courses = await GetCourseSchedule()
          this.initialized = true
        } catch (error: any) {
          console.error('获取课程信息失败:', error)
        }
      }
    },
    async refreshCourseData() {
      try {
        this.courses = await GetCourseSchedule()
      } catch (error) {
        console.error('获取课程信息失败:', error)
      }
    },
    clear() {
      this.courses = []
      this.initialized = false
    }
  }
})
//课程成绩
export const useScoreStore = defineStore('score', {
  state: () => ({
    score: [] as Score[],
    GPA: {} as GPA,
    initialized: false
  }),
  actions: {
    async init() {
      if (!this.initialized) {
        try {
          const res = await GetScore()
          this.score = res.score
          this.GPA = res.gpa
          this.initialized = true
        } catch (error: any) {
          console.error('获取成绩信息失败:', error)
        }
      }
    },
    async refreshScoreData() {
      try {
        const res = await GetScore()
        this.score = res.score
        this.GPA = res.gpa
      } catch (error: any) {
        console.error('获取成绩信息失败:', error)
      }
    },
    clear() {
      this.score = []
      this.GPA = {
        gpa: 0,
        ranking: 0
      }
      this.initialized = false
    }
  }
})
//评价信息
export const useEstimationStore = defineStore('estimation', {
  state: () => ({
    practice: 0,
    moral: 0,
    attitude: 0,
    total: 0,
    initialized: false
  }),
  actions: {
    async init() {
      if (!this.initialized) {
        try {
          const res = await GetEstimation()
          this.practice = res.practice
          this.moral = res.moral
          this.attitude = res.attitude
          this.total = res.total
        } catch (error: any) {
          console.error('获取评价信息失败:', error)
        }
      }
    },
    async refreshData() {
      try {
        const res = await GetEstimation()
        this.practice = res.practice
        this.moral = res.moral
        this.attitude = res.attitude
        this.total = res.total
      } catch (error: any) {
        console.error('获取评价信息失败:', error)
      }
    },
    clear() {
      this.practice = 0
      this.moral = 0
      this.attitude = 0
      this.total = 0
    }
  }
})
